<template>
  <a-list
    class="list-demo-action-layout"
    :data="dataList"
    :pagination-props="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total,
    }"
    @page-change="onPageChange"
  >
    <template #item="{ item }">
      <a-list-item class="list-demo-item" action-layout="vertical">
        <template #actions>
          <!--点赞-->
          <span class="action" key="heart" @click="onPostThumb(item)">
            <span v-if="item.hasThumb">
              <IconHeartFill :style="{ color: '#f53f3f' }" />
            </span>
            <span v-else>
              <IconHeart />
            </span>
            {{ item.thumbNum }}
          </span>
          <!-- 收藏 -->
          <span class="action" key="star" @click="onPostStar(item)">
            <span v-if="item.hasFavour">
              <IconStar :style="{ color: '#ff7d00' }" />
            </span>
            <span v-else>
              <IconStar />
            </span>
            {{ item.favourNum }}
          </span>
          <a-button type="text" @click="showDetail(item)">查看详情</a-button>
        </template>
        <a-list-item-meta :title="item.title" :description="item.content">
          <template #avatar>
            <a-avatar shape="square">
              <img alt="avatar" :src="avatarUrl" />
            </a-avatar>
          </template>
        </a-list-item-meta>
      </a-list-item>
    </template>
  </a-list>
  <!-- 详情模态框 -->
  <a-modal v-model:visible="detailVisible" title="帖子详情" width="768px">
    <div :style="{ display: 'flex' }">
      <a-card>
        <template #title>
          <a-link>{{ selectedPost?.title }}</a-link>
        </template>
        {{ selectedPost?.content }}
      </a-card>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref, defineProps, watchEffect } from "vue";
import {
  PostControllerService,
  PostFavourControllerService,
  PostQueryRequest,
  PostThumbControllerService,
  PostVO,
  UserControllerService,
} from "../../../generated";
import {
  IconHeart,
  IconStar,
  IconHeartFill,
} from "@arco-design/web-vue/es/icon";
import message from "@arco-design/web-vue/es/message";

const props = defineProps({
  isFavour: {
    type: Boolean,
    default: false,
  },
});
const dataList = ref([]);

const total = ref(0);

const searchParams = ref<PostQueryRequest>({
  title: "",
  tags: [],
  pageSize: 8,
  current: 1,
  sortField: "createTime",
  sortOrder: "descend",
});

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
let timer;
watchEffect(() => {
  if (timer) clearTimeout(timer);
  timer = setTimeout(() => {
    loadData();
  }, 300); // 延迟 300ms 执行
});
/**
 *页面加载时,请求数据
 */
onMounted(() => {
  loadData();
});

//头像
const avatarUrl = ref("");

/**
 * content?: string;
 *     current?: number;
 *     favourUserId?: number;
 *     id?: number;
 *     notId?: number;
 *     orTags?: Array<string>;
 *     pageSize?: number;
 *     searchText?: string;
 *     sortField?: string;
 *     sortOrder?: string;
 *     tags?: Array<string>;
 *     title?: string;
 *     userId?: number;
 */
const loadData = async () => {
  if (props.isFavour) {
    const res =
      await PostFavourControllerService.listMyFavourPostByPageUsingPost(
        searchParams.value
      );
    const userData = await UserControllerService.getUserByIdUsingGet(
      res.data.userId
    );
    avatarUrl.value =
      userData.data?.userAvatar ||
      "https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp";
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败，" + res.message);
    }
  } else {
    const res = await PostControllerService.listPostVoByPageUsingPost(
      searchParams.value
    );
    const userData = await UserControllerService.getUserByIdUsingGet(
      res.data.userId
    );
    avatarUrl.value =
      userData.data?.userAvatar ||
      "https://p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/3ee5f13fb09879ecb5185e440cef6eb9.png~tplv-uwbnlip3yd-webp.webp";
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败，" + res.message);
    }
  }
};

//帖子点赞/取消
/**
 * postId?: number;
 */
const onPostThumb = async (post: PostVO) => {
  const res = await PostThumbControllerService.doThumbUsingPost({
    postId: post.id,
  });

  if (res.code === 0) {
    //更新本地数据
    post.hasThumb = !post.hasThumb;
    loadData();
    // post.thumbNum += post.hasThumb ? 1 : -1;
    message.success(post.hasThumb ? "点赞成功" : "取消点赞成功");
  } else {
    message.error("操作失败");
  }
};

/**
 * 帖子收藏/取消
 */
const onPostStar = async (post: PostVO) => {
  // 模拟收藏接口调用
  const res = await PostFavourControllerService.doPostFavourUsingPost({
    postId: post.id,
  });

  if (res.code === 0) {
    // 更新本地数据，避免重新加载整个列表
    post.hasFavour = !post.hasFavour;
    loadData();
    // post.favourNum += post.hasFavour ? 1 : -1;
    message.success(post.hasFavour ? "收藏成功" : "取消收藏成功");
  } else {
    message.error("操作失败");
  }
};

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const detailVisible = ref(false);
const selectedPost = ref(null);

// 显示详情
const showDetail = (post: PostVO) => {
  selectedPost.value = post;
  detailVisible.value = true;
};
</script>

<style scoped></style>
